//
//  EWChangePhoneNumberVC.m
//  haveSomethingToEat
//
//  Created by 陈 宁权 on 17/4/12.
//  Copyright © 2017年 陈 宁权. All rights reserved.
//

#import "EWChangePhoneNumberVC.h"
#import "EWTextField.h"

@interface EWChangePhoneNumberVC ()
@property (nonatomic,strong) EWTextField *phoneNumber;
@property (nonatomic,strong) UITextField *VFCode;
@property (nonatomic,strong) UIButton *getVerificationBtn;
@property (nonatomic,strong) NSTimer *countDownTimer;
@end

static NSInteger secondsCountDown = 60;

@implementation EWChangePhoneNumberVC

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.tabBarController.tabBar setHidden:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.view setBackgroundColor:[UIColor whiteColor]];
    //配置导航栏
    [self configNav];
    //添加子视图
    [self addChildViews];
    
    if ([self respondsToSelector:@selector(edgesForExtendedLayout)])
    {
        self.edgesForExtendedLayout = UIRectEdgeBottom;
    }
}

- (void)configNav
{
    [self.navigationItem setTitle:@"换绑手机号"];
}

- (void)addChildViews
{
    UILabel *phoneNumberLeftView = [[UILabel alloc] init];
    phoneNumberLeftView.frame = CGRectMake(0, 0, 70, 30);
    phoneNumberLeftView.font = [UIFont systemFontOfSize:13];
    phoneNumberLeftView.textAlignment = NSTextAlignmentCenter;
    phoneNumberLeftView.text = @"手机号";
    
    _getVerificationBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_getVerificationBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    [_getVerificationBtn addTarget:self action:@selector(getCode) forControlEvents:UIControlEventTouchUpInside];
    _getVerificationBtn.backgroundColor = [UIColor colorWithRed:133/255.0 green:32/255.0 blue:133/255.0 alpha:1];
    _getVerificationBtn.titleLabel.textColor = [UIColor whiteColor];
    _getVerificationBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    _getVerificationBtn.layer.cornerRadius = 5;
    _getVerificationBtn.layer.masksToBounds = YES;
    _getVerificationBtn.frame = CGRectMake(0, 0, 80, 30);
    
    _phoneNumber = [[EWTextField alloc] init];
    _phoneNumber.placeholder = @"请输入手机号";
    _phoneNumber.font = [UIFont systemFontOfSize:13];
    _phoneNumber.borderStyle = UITextBorderStyleRoundedRect;
    _phoneNumber.layer.cornerRadius = 5;
    _phoneNumber.layer.masksToBounds = YES;
    
    _phoneNumber.leftView = phoneNumberLeftView;
    _phoneNumber.leftViewMode = UITextFieldViewModeAlways;
    
    _phoneNumber.rightView = _getVerificationBtn;
    _phoneNumber.rightViewMode = UITextFieldViewModeAlways;
    [self.view addSubview:_phoneNumber];
    
    _VFCode = [[UITextField alloc] init];
    _VFCode.font = [UIFont systemFontOfSize:13];
    _VFCode.borderStyle = UITextBorderStyleRoundedRect;
    _VFCode.layer.cornerRadius = 5;
    _VFCode.layer.masksToBounds = YES;
    _VFCode.placeholder = @"请输入收到的验证码";
    [self.view addSubview:_VFCode];
    
    UIButton *confirmBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [confirmBtn addTarget:self action:@selector(confirm) forControlEvents:UIControlEventTouchUpInside];
    [confirmBtn setTitle:@"验证后绑定新手机号" forState:UIControlStateNormal];
    confirmBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    confirmBtn.layer.cornerRadius = 5;
    confirmBtn.layer.masksToBounds = YES;
    [confirmBtn setBackgroundColor:[UIColor colorWithRed:133/255.0 green:32/255.0 blue:133/255.0 alpha:1]];
    confirmBtn.titleLabel.textColor = [UIColor whiteColor];
    [self.view addSubview:confirmBtn];
    
    [_phoneNumber mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(40);
        make.left.equalTo(self.view).offset(5);
        make.right.equalTo(self.view).offset(-5);
        make.height.offset(40);
    }];
    
    [_VFCode mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_phoneNumber.mas_bottom).offset(1);
        make.left.equalTo(self.view).offset(5);
        make.right.equalTo(self.view).offset(-5);
        make.height.offset(40);
    }];
    
    [confirmBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_VFCode.mas_bottom).offset(10);
        make.left.equalTo(self.view).offset(5);
        make.right.equalTo(self.view).offset(-5);
        make.height.offset(40);
    }];
}

- (void)getCode
{
    if ([self isMobileNumber:_phoneNumber.text]) {
        __weak typeof(self) weakself = self;
        self.getVerificationBtn.enabled = NO;
        //发送短信验证码
        [SMSSDK getVerificationCodeByMethod:SMSGetCodeMethodSMS phoneNumber:_phoneNumber.text zone:@"86" customIdentifier:nil result:^(NSError *error) {
            if (!error) {
                NSLog(@"验证码发送成功");
                [weakself.phoneNumber endEditing:YES];
                weakself.phoneNumber.enabled = NO;
                weakself.countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(countDownAction) userInfo:nil repeats:YES];
                [weakself.getVerificationBtn setTitle:[NSString stringWithFormat:@"已发送(%lds)",secondsCountDown] forState:UIControlStateNormal];
                weakself.getVerificationBtn.backgroundColor = [UIColor grayColor];
            }
            else
            {
                weakself.getVerificationBtn.enabled = YES;
                NSLog(@"error=%@",error);
            }
        }];
    }
    else
    {
        [SVProgressHUD showErrorWithStatus:@"请输入正确的电话号码"];
    }
}

- (void)confirm
{
    if (_VFCode.text.length > 0) {
        [_VFCode endEditing:YES];
        __weak typeof(self) weakself = self;
        [SMSSDK commitVerificationCode:_VFCode.text phoneNumber:_phoneNumber.text zone:@"86" result:^(SMSSDKUserInfo *userInfo, NSError *error) {
           
            if (!error) {
                NSLog(@"验证成功");
                [[BQUserDao shareObject] updateUserInfoWithUserId:[DEFAULTS objectForKey:@"userId"] andUserName:[DEFAULTS objectForKey:@"userName"] andUserMobile:_phoneNumber.text andPortraitUri:[DEFAULTS objectForKey:@"portraitUri"] andServiceReceiveResponseSuccess:^(id response) {
                    
                    [[NSUserDefaults standardUserDefaults] setObject:_phoneNumber.text forKey:@"userMobile"];
                    //发送通知电话号码更改了
                    [[NSNotificationCenter defaultCenter] postNotificationName:NSNOTIFICATION_PHONENUMBER_CHANGED object:nil];
                    //回到上级页面
                    [weakself.navigationController popViewControllerAnimated:YES];
                    
                } ServiceReceiveResponseFailed:^(id response) {
                    [SVProgressHUD showErrorWithStatus:@"更改用户名失败，请稍后重试!"];
                }];
                
            }
            else
            {
                [SVProgressHUD showErrorWithStatus:@"验证失败请输入正确的验证码"];
            }
        }];
    }
    else
    {
        [SVProgressHUD showErrorWithStatus:@"请输入验证码"];
    }
}


- (void)countDownAction
{
    secondsCountDown--;
    [_getVerificationBtn setTitle:[NSString stringWithFormat:@"已发送(%lds)",secondsCountDown] forState:UIControlStateNormal];
    if (secondsCountDown == 0) {
        [_countDownTimer invalidate];
        [_getVerificationBtn setTitle:@"发送验证码" forState:UIControlStateNormal];
        _getVerificationBtn.backgroundColor = [UIColor colorWithRed:133/255.0 green:32/255.0 blue:133/255.0 alpha:1];
        _getVerificationBtn.enabled = YES;
        _phoneNumber.enabled = YES;
        secondsCountDown = 60;
    }
}

//判断电话号码是否有效
- (BOOL)isMobileNumber:(NSString *)mobileNum
{
    NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$";
    NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$";
    NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
    NSString * CT = @"^1((33|53|8[09])[0-9]|349)\\d{7}$";
    // NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    if (([regextestmobile evaluateWithObject:mobileNum] == YES)
        || ([regextestcm evaluateWithObject:mobileNum] == YES)
        || ([regextestct evaluateWithObject:mobileNum] == YES)
        || ([regextestcu evaluateWithObject:mobileNum] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
